<template>
  <div class="">
    <nil-page icon="search" title="数据查询" margin-bottom>
      <nil-search :form="user_form" @search="search"></nil-search>
    </nil-page>

    <nil-page icon="paperclip" title="数据列表">
      <template #option>
        <el-button type="primary" @click="handleAdd()"> 添加用户 </el-button>
      </template>
      <nil-thin-table
        :data="tableData"
        :columns="user_columns"
        :loading="tableDataLoading"
      >
        <template #status="{ row }">
          <el-tag :type="row.status == '0' ? 'success' : 'danger'">{{
            STATUS_MAP[row.status]
          }}</el-tag>
        </template>
        <template #roleId="{ row }">
          <el-tag type="success">{{ ROLE_MAP[row.roleId] ?? "未知" }}</el-tag>
        </template>
        <template #option="{ row }">
          <el-button type="primary" @click="handleEdit(row)"> 修改 </el-button>
          <el-button
            :type="row.status == '0' ? 'danger' : 'success'"
            @click="handleDelete(row)"
          >
            {{ row.status == "0" ? "禁用" : "启用" }}
          </el-button>
        </template>
      </nil-thin-table>
      <div style="margin-top: 10px">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :page-size="page.size"
          :total="page.total"
          @current-change="pageChange"
        ></el-pagination>
      </div>
    </nil-page>
    <el-drawer
      v-model="addAndChangeBox"
      :title="`${isChange ? '修改' : '创建'}用户`"
      direction="rtl"
      destroy-on-close
      size="40%"
    >
      <ac-box
        :data="oneData"
        :loading="oneDataLoading"
        :isChange="isChange"
        :roles="roles"
        @change="change"
        @save="save"
        @cancel="addAndChangeBox = false"
      />
    </el-drawer>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref } from "vue";
import { user_columns } from "@/config/table.sys";
import { user_form } from "@/config/search.form";
import AcBox from "./AcBox.vue";
import api from "@/http/api";
import md5 from "js-md5";
import {
  ADMIN_ROLE_LIST,
  ADMIN_USER_CHANGE,
  ADMIN_USER_LIST,
  ADMIN_USER_STATUS,
} from "@/http/uri";
import { ElMessage, ElMessageBox } from "element-plus";
// import AcBox from "./AcBox.vue";
// 表 是否 加载中
const tableDataLoading = ref(false);
// 表数据
const tableData = ref([]);
const page = reactive({
  cur: 1,
  size: 10,
  total: 0,
  key: "",
});

const STATUS_MAP = ["正常", "禁用"];
const ROLE_MAP = ref({});
const roles = ref([]);

function initRoles() {
  api.GET(ADMIN_ROLE_LIST).then((res) => {
    if (res.success) {
      console.log("[ res ] >", res);
      roles.value = res.data;
      res.data.forEach((element) => {
        ROLE_MAP.value[element.id] = element.roleName;
      });
      initData();
    }
  });
}

function pageChange(cur) {
  page.cur = cur;
  initData();
}

// 加载数据
const initData = () => {
  tableDataLoading.value = true;
  api
    .GET(ADMIN_USER_LIST, {
      current: page.cur,
      size: page.size,
      key: page.key ?? "",
    })
    .then((res) => {
      if (res.success) {
        tableData.value = res.data.records;
        page.cur = res.data.current;
        page.size = res.data.size;
        page.total = res.data.total;
      }
    })
    .finally(() => {
      tableDataLoading.value = false;
    });
};

// vue 生命周期 hook
onMounted(() => {
  initRoles();
});

// 搜索
const search = ({ key }) => {
  console.log(key);
  page.cur = 1;
  page.key = key ?? "";
  console.log("[ data ] >", key);
  initData();
};

const isChange = ref(false);
const oneDataLoading = ref(false);
const addAndChangeBox = ref(false);
const oneData = reactive({
  id: "",
  account: "",
  password: "",
  name: "",
  roleId: "",
  status: "",
});

let _oneDataBackJSON = "";

function handleAdd() {
  oneData.id = "";
  oneData.account = "";
  oneData.password = "";
  oneData.name = "";
  oneData.roleId = "";
  oneData.status = "";

  isChange.value = false;
  addAndChangeBox.value = true;
}

function handleEdit(row) {
  oneData.id = row.id ?? "";
  oneData.account = row.account ?? "";
  oneData.password = row.password ?? "";
  oneData.name = row.name ?? "";
  oneData.roleId = row.roleId ?? "";
  oneData.status = row.status ?? "";

  isChange.value = true;
  addAndChangeBox.value = true;
  _oneDataBackJSON = JSON.stringify(oneData);
}

// 删除
const handleDelete = (row) => {
  console.log(row);
  const hint = row.status == "0" ? "禁用" : "启用";
  ElMessageBox.confirm(`是否要进行 ${hint} 操作, 是否继续?`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      api
        .POST(ADMIN_USER_STATUS, {
          id: row.id ?? "",
          status: row.status ?? "",
        })
        .then((res) => {
          if (res.success) {
            ElMessage.success(res.message);
            initData();
          } else {
            ElMessage.error(res.message);
          }
        });
    })
    .catch(() => {});
};

function save(data) {
  oneDataLoading.value = true;
  let upData = JSON.parse(JSON.stringify(data));
  upData.password = md5(data.password);
  api
    .POST(ADMIN_USER_CHANGE, upData)
    .then((res) => {
      if (res.success) {
        ElMessage.success(res.message);
        addAndChangeBox.value = false;
        // _oneDataBackJSON = "";
        initData();
      } else {
        ElMessage.error(res.message);
      }
      oneDataLoading.value = false;
    })
    .catch(() => {
      oneDataLoading.value = false;
    });
}

const change = (data) => {
  console.log("[ data ] >", data);
  if (_oneDataBackJSON == "") {
    ElMessage.error("修改失败.");
    return;
  }
  if (_oneDataBackJSON == JSON.stringify(data)) {
    ElMessage.error("没有修改内容.");
    return;
  }
  oneDataLoading.value = true;
  oneDataLoading.value = true;
  api
    .PUT(ADMIN_USER_CHANGE, data)
    .then((res) => {
      if (res.success) {
        ElMessage.success(res.message);
        addAndChangeBox.value = false;
        _oneDataBackJSON = "";
        initData();
      } else {
        ElMessage.error(res.message);
      }
      oneDataLoading.value = false;
    })
    .catch(() => {
      oneDataLoading.value = false;
    });
};
</script>
